/* $Id: msguest.c,v 1.3 2006/03/15 03:49:16 jfb Exp $ */
/*
 * Copyright (c) 2003 Jean-Francois Brousseau <phrakt@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/types.h>
#include <sys/socket.h>

#include <netinet/in.h>
#include <arpa/inet.h>

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <canopy/log.h>
#include <canopy/string.h>

#include "msg.h"
#include "conn.h"
#include "http.h"
#include "private.h"


struct http_hdr_info {
	const char  *hdr_name;
	int          hdr_version;
	int        (*hdr_hdlr)(http_hdr_t *, http_msg_t *);
} http_std_hdrs[] = {
	{ "Accept",               HTTP_VERSION_11, NULL  },
	{ "Accept-Charset",       HTTP_VERSION_11, NULL  },
	{ "Accept-Language",      HTTP_VERSION_11, NULL  },
	{ "Accept-Encoding",      HTTP_VERSION_11, NULL  },
	{ "Accept-Ranges",        HTTP_VERSION_11, NULL  },
	{ "Age",                  HTTP_VERSION_11, NULL  },
	{ "Allow",                HTTP_VERSION_10, NULL  },
	{ "Authorization",        HTTP_VERSION_10, NULL  },
	{ "Cache-Control",        HTTP_VERSION_11, NULL  },
	{ "Connection",           HTTP_VERSION_11, NULL  },
	{ "Content-Encoding",     HTTP_VERSION_10, NULL  },
	{ "Content-Language",     HTTP_VERSION_11, NULL  },
	{ "Content-Length",       HTTP_VERSION_10, NULL  },
	{ "Content-Location",     HTTP_VERSION_11, NULL  },
	{ "Content-MD5",          HTTP_VERSION_11, NULL  },
	{ "Content-Range",        HTTP_VERSION_11, NULL  },
	{ "Content-Type",         HTTP_VERSION_10, NULL  },
	{ "Date",                 HTTP_VERSION_10, NULL  },
	{ "ETag",                 HTTP_VERSION_11, NULL  },
	{ "Expect",               HTTP_VERSION_11, NULL  },
	{ "Expires",              HTTP_VERSION_10, NULL  },
	{ "From",                 HTTP_VERSION_10, NULL  },
	{ "Host",                 HTTP_VERSION_11, NULL  },
	{ "If-Match",             HTTP_VERSION_11, NULL  },
	{ "If-Modified-Since",    HTTP_VERSION_10, NULL  },
	{ "If-None-Match",        HTTP_VERSION_11, NULL  },
	{ "If-Range",             HTTP_VERSION_11, NULL  },
	{ "If-Unmodified-Since",  HTTP_VERSION_11, NULL  },
	{ "Last-Modified",        HTTP_VERSION_10, NULL  },
	{ "Location",             HTTP_VERSION_10, NULL  },
	{ "Max-Forwards",         HTTP_VERSION_11, NULL  },
	{ "Pragma",               HTTP_VERSION_10, NULL  },
	{ "Proxy-Authenticate",   HTTP_VERSION_11, NULL  },
	{ "Proxy-Authorization",  HTTP_VERSION_11, NULL  },
	{ "Range",                HTTP_VERSION_11, NULL  },
	{ "Referer",              HTTP_VERSION_10, NULL  },
	{ "Retry-After",          HTTP_VERSION_11, NULL  },
	{ "Server",               HTTP_VERSION_10, NULL  },
	{ "TE",                   HTTP_VERSION_11, NULL  },
	{ "Trailer",              HTTP_VERSION_11, NULL  },
	{ "Transfer-Encoding",    HTTP_VERSION_11, NULL  },
	{ "Upgrade",              HTTP_VERSION_11, NULL  },
	{ "User-Agent",           HTTP_VERSION_10, NULL  },
	{ "Vary",                 HTTP_VERSION_11, NULL  },
	{ "Via",                  HTTP_VERSION_11, NULL  },
	{ "Warning",              HTTP_VERSION_11, NULL  },
	{ "WWW-Authenticate",     HTTP_VERSION_10, NULL  },
};

/*
 * http_hdr_create()
 *
 * Create a new HTTP header with field name <name> and value <val>.
 * Returns a pointer to the new header structure on success, or NULL
 * on failure.
 */
http_hdr_t*
http_hdr_create(const char *name, const char *val)
{
	http_hdr_t *hdr;

	if ((hdr = malloc(sizeof(*hdr))) == NULL) {
		cnp_log(CNP_LOG_ERRNO, "failed to allocate new HTTP header");
		return (NULL);
	}

	if ((hdr->hdr_name = strdup(name)) == NULL) {
		cnp_log(CNP_LOG_ERRNO, "failed to copy header name");
		free(hdr);
		return (NULL);
	}

	if ((hdr->hdr_val = strdup(val)) == NULL) {
		cnp_log(CNP_LOG_ERRNO, "failed to copy header value");
		free(hdr->hdr_name);
		free(hdr);
		return (NULL);
	}

	return (hdr);
}

/*
 * http_hdr_free()
 *
 * Free the HTTP header <hdr> and all of its associated resources.
 */
void
http_hdr_free(http_hdr_t *hdr)
{
	if (hdr->hdr_name != NULL)
		free(hdr->hdr_name);

	if (hdr->hdr_val != NULL)
		free(hdr->hdr_val);

	free(hdr);
}

#if 0
/*
 * http_hdr_format()
 *
 * Format the HTTP msguest <msg> into its HTTP string equivalent.  The result
 * is stored in <dst>, which is of size <dlen>.
 */
ssize_t
http_hdr_format(http_hdr_t *msg, void **dst, size_t *dlen, int flags)
{
	return (0);
}
#endif

/*
 * http_hdr_parse()
 *
 * Parse an HTTP header that starts at <data>, which is of size contained in
 * <len>.  Parsing stops as soon as the header is complete or the end of the
 * buffer is reached first.  
 * If the call is successful, the value of <len> is updated to reflect the
 * number of bytes that were used for the header (including the terminating
 * CRLF sequence).
 * Returns the parsed header structure on success, or NULL on failure.
 */
http_hdr_t*
http_hdr_parse(const void *data, size_t *len)
{
	unsigned int i;
	size_t left = *len;
	char namebuf[64], valbuf[128];
	const uint8_t *ep, *sp = (const uint8_t *)data;
	http_hdr_t *hdr = NULL;

	if ((ep = memchr(sp, HTTP_HDRSEP, *len)) == NULL) {
		cnp_log(CNP_LOG_WARN, "no HTTP header field separator");
		return (NULL);
	}

	memcpy(namebuf, sp, ep - sp);
	namebuf[ep - sp] = '\0';
	left -= (size_t)(ep - sp) - 1;
	sp = ep + 1;

	/*
	 * RFC 2616 specifies that although one space SHOULD be present
	 * after the ':', there MAY be any amount of LWS before and after
	 * the field value, so we strip all of this if it is present.
	 */

	if (!HTTP_MSG_ISLWS(*sp)) {
		cnp_log(CNP_LOG_WARN, "no space after HTTP header field "
		    "separator");
		return (NULL);
	}

	do {
		sp++;
		left--;
	} while (HTTP_MSG_ISLWS(*sp));

	i = 0;
	while ((i < sizeof(valbuf) - 1) && (left > 0)) {
		if (((*sp == '\r') && (left > 1) && (*(sp + 1) == '\n')) ||
		    (*sp == '\n')) {
			left--;
			if (*(sp++) == '\r') {
				left--;
				sp++;
			}

			if (left > 0) {
				if (!HTTP_MSG_ISLWS(*sp))
					break;
				else
					sp++;
			}
		}
		else {
			valbuf[i++] = *(sp++);
			left--;

			/* merge consecutive spaces into a single one */
			while (HTTP_MSG_ISLWS(*sp)) {
				sp++;
				left--;
			}
		}
	}
	valbuf[i] = '\0';

	hdr = http_hdr_create(namebuf, valbuf);
	if (hdr != NULL)
		*len = sp - ((const uint8_t *)data);

	return (hdr);
}
